package com.zcsy.manage.web.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.mall.IntegralRecord;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.manage.service.mall.IIntegralRecordService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title: OwnerTreasureController.java
 * @Package： com.zcsy.manage.web.base 
 * @Description: 业主资产控制层
 * @author yangfan 373188993@qq.com
 * @date 2016年8月2日
 * @version 1.0
 * @see JDK1.7.0_75
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 */

@Controller
@RequestMapping(value = "ownerTreasure")
public class OwnerTreasureController {
    
    @Autowired
    private IIntegralRecordService integralRecordService;
    
    @Autowired
    private ICouponInfoService couponInfoService;

	@Autowired
    private ICouponDetailService couponDetailService;
	
	@Autowired
	private IUserService userService;
	
	public static final int PAGE_SIZE  = 12; //优惠券每页大小
    /**
     * @Description:积分变更列表
     * @param state 积分变更显示状态 0：全部 1：收入 2：支出
     * @author yangfan 373188993@qq.com
     * @date 2016年8月2日
     */
    @RequestMapping(value="ownerIntegralChangeList" , method = RequestMethod.GET)
    public String ownerIntegralChangeList(Model model, HttpServletRequest req , Integer state ,Integer pNo){
        
        // 指定默认为首页
        if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
            pNo = OwnerConstants.PAGE_NO;
        }
        //获取当前登陆的用户的信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		String userAccount = user.getLoginname();
        IntegralRecord integralRecord = new IntegralRecord();

        // 根据integralRecord查询所需信息
        //TODO 数据库加字段后再完成对应sql
        integralRecord.setUserAccount(userAccount);
        integralRecord.setState(state);
        
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);
        
        List<IntegralRecord> integralRecordList = integralRecordService.selectByUserAccount(integralRecord);
        PageInfo<IntegralRecord> integralRecordListP = new PageInfo<IntegralRecord>(integralRecordList);
        
        
        model.addAttribute("integralRecord",integralRecordListP);
        model.addAttribute("state",state);
        model.addAttribute("currentPage",pNo);
        model.addAttribute("userIntegral", user.getIntegral());
        
        return "base/ownertreasure/myIntegral";
        
    }
    
    /**
     * @Description 我的优惠券列表查询
     * @param token
     *            couponState优惠券状态 1:可使用 2：已到期
     * @return result优惠券信息列表
     * @author yangfan 373188993@qq.com
     * @date 2016年6月30日
     */
    @RequestMapping(value = "getCouponList", method = RequestMethod.GET)
    public String getCouponList(Model model, HttpServletRequest req,Integer pNo) {

        // 指定默认为首页
        if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
            pNo = OwnerConstants.PAGE_NO;
        }
        
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String userAccount = user.getLoginname();

        CouponInfo couponInfo = new CouponInfo();
        
        //查询可使用的优惠券
        couponInfo.setUserAccount(userAccount);
        
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, PAGE_SIZE);
        List<CouponInfo> couponInfoList = couponInfoService.selectByUserAccountAndState(couponInfo);
        
        //判断两个字符串的大小用
        int flag=0;
        //1：可用 2：已过期
        int COUPON_CAN_USE =1;
        int COUPON_CANNOT_USE =2;
        
        if (!couponInfoList.isEmpty()) {
            
            //循环操作赋值couponState，可用且未过期=1，已过期=2
            for(CouponInfo c:couponInfoList) {
                if(DateUtils.getTodayDate().compareTo(c.getUseEndDate()) < flag || DateUtils.getTodayDate().compareTo(c.getUseEndDate()) == flag ) {
                    c.setCouponState(COUPON_CAN_USE);
                } else {
                    c.setCouponState(COUPON_CANNOT_USE);
                }
                c.setUseBeginDate(c.getUseBeginDate().replace('-', '.'));
                c.setUseEndDate(c.getUseEndDate().replace('-', '.'));
            }
        } 

        PageInfo<CouponInfo> record = new PageInfo<CouponInfo>(couponInfoList);
        model.addAttribute("record",record);
        model.addAttribute("currentPage",pNo);
        
        return "base/ownertreasure/myCoupon";

    }
    
    /**
     * @Description 领取优惠券
     * @param couponId 优惠券id
     * @return 获取结果
     * @author liuying 1075817474@qq.com
     * @date 2016年8月5日
     * @see 
     */
    @RequestMapping(value = "getCoupon", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson getCoupon(String couponId ,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String userAccount = user.getLoginname();
        
        //根据优惠券id获取优惠券信息
        CouponInfo couponInfo = null;
        
        synchronized (couponId) {
        	
    		if(couponId != null) {
    			
	    		couponInfo = couponInfoService.selectByPrimaryKey(couponId);
	    		if(couponInfo.getCount() >= 1){
	    			
	    			CouponDetail cDetail = couponDetailService.selectByUserAccountAndCouponId(couponId, userAccount);
	    			
	    			if(cDetail == null){
	    				// 生成18位id
	    		        String id = UniqueNumberUtils.get18UniqueNumber();
	
	    		        //添加领取优惠券信息
	    		        CouponDetail couponDetail = new CouponDetail();
	    		        couponDetail.setId(id);
	    		        couponDetail.setCouponId(couponId);
	    		        couponDetail.setState(couponInfo.getState());
	    		        couponDetail.setPhone(user.getPhone());
	    		        couponDetail.setUserAccount(userAccount);
	    		        couponDetail.setExpireTime(DateUtils.str2Date(couponInfo.getUseEndDate() , DateUtils.date_sdf));
	    		        couponDetail.setCreateTime(DateUtils.gettimestamp());
	    		        couponDetailService.insert(couponDetail);
	    		        
	    		        //优惠劵数量减一
	    		        couponInfoService.updateCouponCount(couponInfo);
	    		        
	    		        result.setSuccess(true);
	    	            result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
	    	            result.setMsg("优惠券领取成功，快去使用吧！");
	    		        
	    			} else {
	    				result.setMsg("您已领取此优惠劵" );
	    			}
	    			
	    		} else {
	    			result.setSuccess(false);
	                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
	                result.setMsg("优惠券抢完了，下次再来吧！");
	                return result;
	    		}
	    		
    		} else {
    			result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("优惠券领取失败！");
    		}
		}
        return result;
    }
}
